<template>
  <div class="analysis-container">
    <div class="header">
      <h2>数据统计分析</h2>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="8">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>用户总数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="data-value">{{ userCount }}</div>
            <div class="data-icon">
              <el-icon><User /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>门店总数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="data-value">{{ storeCount }}</div>
            <div class="data-icon">
              <el-icon><Shop /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>药品总数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="data-value">{{ medicineCount }}</div>
            <div class="data-icon">
              <el-icon><FirstAidKit /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

  


  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Shop, FirstAidKit } from '@element-plus/icons-vue'
import { listUser } from '@/api/user'
import { listStore } from '@/api/store'
import { listMedicine } from '@/api/medicine'

// 数据统计
const userCount = ref(0)
const storeCount = ref(0)
const medicineCount = ref(0)

// 图表引用
const userRoleChartRef = ref(null)
const medicineStatusChartRef = ref(null)
const dataComparisonChartRef = ref(null)

// 图表实例
let userRoleChart = null
let medicineStatusChart = null
let dataComparisonChart = null

// 获取用户数据
const getUserData = async () => {
  try {
    const res = await listUser({})
    userCount.value = res?.length || 0

    // 计算用户角色分布
    const roleData = {
      用户: 0,
      门店: 0,
      管理员: 0
    }

    res?.forEach((user) => {
      if (user.role === 0) roleData['用户']++
      else if (user.role === 1) roleData['门店']++
      else if (user.role === 2) roleData['管理员']++
    })

    // 渲染用户角色分布图表

    return res || []
  } catch (error) {
    console.error('获取用户数据失败', error)
    ElMessage.error('获取用户数据失败')
    return []
  }
}

// 获取门店数据
const getStoreData = async () => {
  try {
    const res = await listStore({})
    storeCount.value = res?.length || 0
    return res || []
  } catch (error) {
    console.error('获取门店数据失败', error)
    ElMessage.error('获取门店数据失败')
    return []
  }
}

// 获取药品数据
const getMedicineData = async () => {
  try {
    const res = await listMedicine({})
    medicineCount.value = res?.length || 0

    // 计算药品状态分布
    const statusData = {
      在售: 0,
      停售: 0
    }

    res?.forEach((medicine) => {
      if (medicine.status === 0) statusData['在售']++
      else if (medicine.status === 1) statusData['停售']++
    })

    // 渲染药品状态分布图表

    return res || []
  } catch (error) {
    console.error('获取药品数据失败', error)
    ElMessage.error('获取药品数据失败')
    return []
  }
}

// 渲染用户角色分布图表
const renderUserRoleChart = (data) => {
  if (!userRoleChartRef.value) return

  userRoleChart = echarts.init(userRoleChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: Object.keys(data)
    },
    series: [
      {
        name: '用户角色',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.keys(data).map((key) => ({
          value: data[key],
          name: key
        }))
      }
    ]
  }

  userRoleChart.setOption(option)
}

// 渲染药品状态分布图表
const renderMedicineStatusChart = (data) => {
  if (!medicineStatusChartRef.value) return

  medicineStatusChart = echarts.init(medicineStatusChartRef.value)

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: Object.keys(data)
    },
    series: [
      {
        name: '药品状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.keys(data).map((key) => ({
          value: data[key],
          name: key
        }))
      }
    ]
  }

  medicineStatusChart.setOption(option)
}

// 渲染数据对比图表
const renderDataComparisonChart = () => {
  if (!dataComparisonChartRef.value) return

  dataComparisonChart = echarts.init(dataComparisonChartRef.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['数据统计']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '用户',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: [userCount.value]
      },
      {
        name: '门店',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: [storeCount.value]
      },
      {
        name: '药品',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: [medicineCount.value]
      }
    ]
  }

  dataComparisonChart.setOption(option)
}

// 初始化数据
const initData = async () => {
  await Promise.all([getUserData(), getStoreData(), getMedicineData()])

  // 渲染数据对比图表
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  userRoleChart?.resize()
  medicineStatusChart?.resize()
  dataComparisonChart?.resize()
}

onMounted(() => {
  initData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除事件监听
const onUnmounted = () => {
  window.removeEventListener('resize', handleResize)
  userRoleChart?.dispose()
  medicineStatusChart?.dispose()
  dataComparisonChart?.dispose()
}
</script>

<style scoped>
.analysis-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 150px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80px;
}

.data-value {
  font-size: 36px;
  font-weight: bold;
  color: #409eff;
}

.data-icon {
  font-size: 48px;
  color: #909399;
  opacity: 0.3;
}

.chart-container {
  margin-bottom: 20px;
}

.chart {
  height: 300px;
}
</style>
